package net.xumf.service.master.impl;

import com.google.common.collect.Lists;
import net.xumf.dao.master.SystemPermissionRepository;
import net.xumf.domain.master.SystemPermission;
import net.xumf.service.master.SystemPermissionService;
import net.xumf.support.common.BaseServiceImpl;
import net.xumf.support.converter.PageConverter;
import net.xumf.support.model.dto.PageDTO;
import net.xumf.support.model.vo.PageVO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class SystemPermissionServiceImpl extends BaseServiceImpl<SystemPermissionRepository, SystemPermission, Integer> implements SystemPermissionService {

    @Override
    public List<SystemPermission> getByPermissionIdIn(String permissionIdsString) {
        if (StringUtils.isEmpty(permissionIdsString)) {
            return Lists.newArrayList();
        }
        List<Integer> permissionIds = Arrays.stream(permissionIdsString.split(","))
                .map(Integer::parseInt).distinct().collect(Collectors.toList());
        return repository.findByPermissionIdIn(permissionIds);
    }

    @Override
    public List<SystemPermission> getByPermissionIdIn(List<String> permissionIdsStrings) {
        Optional<String> permissionIdsString = permissionIdsStrings.stream()
                .filter(o -> !StringUtils.isEmpty(o)).reduce((a, b) -> a + ',' + b);
        return getByPermissionIdIn(permissionIdsString.orElse(""));
    }

    @Override
    public PageVO getByModuleIdAndPage(Integer parentId, PageDTO pageDTO) {
        Pageable pageable = PageConverter.pageVOToPageable(pageDTO);
        Page<SystemPermission> systemPermissionPage = repository.findByModuleId(parentId, pageable);
        return PageConverter.pageToPageDTO(systemPermissionPage);
    }

    @Override
    public void removeByModuleIdIn(List<Integer> moduleIds) {
        repository.deleteByModuleIdIn(moduleIds);
    }

    @Override
    public List<SystemPermission> getAllWithModulePath() {
        return repository.findAll();
    }

}
